<?php


namespace addon\hotel\model;


use app\model\BaseModel;

class RoomStock extends BaseModel
{
    /**
     * 增加库存
     * @param $param
     */
    public function incStock($param)
    {
        $condition = array(
            [ "room_id", "=", $param["room_id"] ]
        );
        $num = $param["room_num"];
        $sku_info = model("hotel_room")->getInfo($condition, "room_id,stock");
        if (empty($sku_info))
            return $this->error(-1, "");

        //编辑sku库存
        $result = model("hotel_room")->setInc($condition, "stock", $num);

        return $this->success($result);
    }

    /**
     * 减少库存
     * @param $param
     */
    public function decStock($param)
    {
        model("hotel_room")->startTrans();
        //循环生成多个订单
        try {
            $condition = array(
                [ "room_id", "=", $param["room_id"] ]
            );
            $num = $param["room_num"];
            //编辑sku库存
            $result = model("hotel_room")->setDec($condition, "stock", $num);
            if ($result === false){
                model("hotel_room")->rollback();
                return $this->error();
            }

            $sku_info = model("hotel_room")->getInfo($condition, "room_id,stock,room_name");
            if (empty($sku_info)){
                model("hotel_room")->rollback();
                return $this->error();
            }

            if ($sku_info["stock"] < 0){
                model("hotel_room")->rollback();
                return $this->error('', $sku_info["room_name"] . "已售罄!");
            }

            model("hotel_room")->commit();
            return $this->success($result);
        } catch ( \Exception $e ) {
            model("hotel_room")->rollback();
            return $this->error('', $e->getMessage());
        }
    }
}